# coding=utf8
# 全世界最帅的帅哥
from flask import request, g, current_app
from flask_restful import Resource, reqparse
from comment.modules.bank_card import BankCard
from comment.modules import db
from comment.modules.user import User


class CardResource(Resource):
    """
    银行卡管理的资源类
    """

    def post(self):
        """添加银行卡"""
        rp = reqparse.RequestParser()
        rp.add_argument("holder", required=True)  # 持卡人 账户名
        rp.add_argument("openingBank", required=True)  # 开户行
        rp.add_argument("bankBranch", required=True)  # 支行
        rp.add_argument("cityId", required=True)  # 城市ID
        rp.add_argument("cardNum", required=True)  # 卡号

        args = rp.parse_args()
        holder = args.holder
        opening_bank = args.openingBank
        bank_branch = args.bankBranch
        city_id = args.cityId
        card_num = args.cardNum

        # 验证银行卡是否唯一
        card_info = BankCard.query.filter(BankCard.bankCardNum == card_num).first()
        if card_info:
            return {"message": "银行卡已经存在，请勿重复添加", "code": 20001}

        # 添加到数据库中
        user_id = g.user_id
        login_user = User.query.filter(User.id == user_id).first()
        card = BankCard(bankCardNum=card_num, openingBank=opening_bank, cityId=city_id, bankBranch=bank_branch,
                        userId=user_id, holder=holder, reservePhone=login_user.phone)
        db.session.add(card)
        db.session.commit()
        return {"msg": "添加银行卡成功"}

    def get(self):
        """
        查询当前登录用户的银行卡
        :return:
        """
        user_id = g.user_id

        card_list = BankCard.query.filter(BankCard.userId == user_id).all()
        if card_list:  # 把对象转换成字典对象
            from .serializer import BandCardListSerializer
            return BandCardListSerializer(card_list).to_dict()
        else:
            return {}

    def delete(self):
        """
        删除当前用户的银行卡
        :return:
        """
        rp = reqparse.RequestParser()
        rp.add_argument("cardId", required=True)
        args = rp.parse_args()
        card_id = args.cardId

        card = BankCard.query.filter(BankCard.bankInfoId == card_id).first()
        if card:
            db.session.delete(card)
            db.session.commit()
            return {"msg": "删除银行卡成功!"}
        else:
            return {"message": "银行卡不存在，删除错误!"}